const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 发送验证码
 */
exports.main = async (event, context) => {
  try {
    const { OPENID } = cloud.getWXContext()
    const { phone } = event
    const code = (1000000 + Math.random() * 999999).toFixed().substr(1)
    const result = await sendSms(phone, code)

    if (result.code === 0) {
      const create = Date.now()
      await db.collection('sent_code')
        .add({
          data: { _openid: OPENID, phone, code, status: 0, create }
        })
    }

    return result
  } catch (err) {
    return {
      code: -1,
      message: err
    }
  }
}

/*
* 功能：通过 SDK 发送短信
* 参数：手机号、短信验证码
*/
function sendSms(phone, code) {
  const tencentcloud = require('tencentcloud-sdk-nodejs')
  const SmsClient = tencentcloud.sms.v20190711.Client
  const Credential = tencentcloud.common.Credential
  const ClientProfile = tencentcloud.common.ClientProfile
  const HttpProfile = tencentcloud.common.HttpProfile
  // 腾讯云账户 secretId，secretKey，切勿泄露
  const secretId = "AKIDWoqeGew1lFTYWFT5xlKUPVMwINWWlqAN" // 需要配置为真实的 secretId
  const secretKey = "Cq9uQgnecKmyxhCN0DbizhMq67sOfmkU" // 需要配置为真实的 secretKey

  let cred = new Credential(secretId, secretKey)
  let httpProfile = new HttpProfile()
  httpProfile.endpoint = "sms.tencentcloudapi.com"
  let clientProfile = new ClientProfile()
  clientProfile.httpProfile = httpProfile
  let client = new SmsClient(cred, "ap-guangzhou", clientProfile)
  phone = "+86" + phone // 国内手机号

  let req = {
    PhoneNumberSet: [phone], // 发送短信的手机号
    TemplateID: "634143", // 步骤1.2 中创建并记录的模板 ID
    Sign: "应云网络", // 步骤1.1 中创建的签名
    TemplateParamSet: [code], // 随机验证码
    SmsSdkAppid: "1400385555" // 短信应用 ID
  }

  function smsPromise() {
    return new Promise((resolve, reject) => {
      client.SendSms(req, function (errMsg, response) {
        if (errMsg) {
          resolve({
            code: -1,
            data: errMsg
          })
        } else {
          if (response.SendStatusSet && response.SendStatusSet[0] && response.SendStatusSet[0].Code === "Ok") {
            resolve({
              code: 0,
              message: response.SendStatusSet[0].Message
            })
          } else {
            let message = '发送失败！'
            const code = response.SendStatusSet[0].Code
            switch (code) {
              case 'LimitExceeded.PhoneNumberDailyLimit':
                message = '此手机号已超出今日的验证码发送次数上限！'
                break
              case 'LimitExceeded.PhoneNumberSameContentDailyLimit':
                message = '此手机号已超出一小时内的验证码发送次数上限！'
                break
              case 'LimitExceeded.PhoneNumberThirtySecondLimit':
                message = '请不要重复发送验证码！'
                break
            }
            resolve({
              code: -1,
              message
            })
          }
        }
      });
    })
  }

  return smsPromise()
}